package com.lw.ai.controller;

import com.lw.ai.enums.DataType;
import com.lw.ai.model.Book;
import com.lw.ai.model.Result;
import com.lw.ai.model.ResultNew;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/book")
public class UserController {
    //增加一个 map集合 存储图书信息
    Map<String, Book> map=new HashMap<>();
    {
        Book book=new Book();
        book.setNumber("1001");
        book.setBookName("java从入门到精通");
        book.setPrice(99.9);
        book.setPublish("清华大学出版社");
        map.put(book.getNumber(),book);
        Book book1=new Book();
        book1.setNumber("1002");
        book1.setBookName("Python从入门到精通");
        book1.setPrice(199.9);
        book1.setPublish("清华大学出版社");
        map.put(book1.getNumber(),book1);

    }



    @GetMapping()
    public ResultNew showBook(){
        return ResultNew.success(map,DataType.BOOK_LIST);///
    }

    @GetMapping("/error")
    public ResultNew showError(){
        return ResultNew.failure(404,"戳错了 ...稍后再试");///
    }




    @GetMapping("/1/{id}")
    public Result<Book> showBookById( @PathVariable String id){
        System.out.println(id);
        return Result.success(map.get(id));
    }
    @GetMapping("/2/{name}")
    public Book showBookByBookname( @PathVariable String name){
        //System.out.println(id);
        return null;
    }
    @PostMapping()
    public String addBook(@RequestBody Book book){   //增加一本书  json
        if(book==null||book.getNumber()==null)
            return "出错了";
        else
            System.out.println(book);
            map.put(book.getNumber(),book);
        return "增加成功";
    }
    //  修改一本
    @PutMapping()
    public String updateBook(@RequestBody Book book) {   //增加一本书  json
        if (book == null || book.getNumber() == null)  //没有传入数据
            return "出错了";
        else if(!map.containsKey(book.getNumber())){
            return "没有此书，不能修改";
        }
        map.put(book.getNumber(), book);
        return "修改成功";
    }
    //删除一本书
    @DeleteMapping("/{id}")
    public String deleteBook(@PathVariable String id){
        if(id==null||!map.containsKey(id))
            return "没有此书，不能删除";
        map.remove(id);
        return "删除成功";
    }
}
